package com.lianyi.push.share.tcpservice;

import com.lianyi.push.share.ConstantValue;
import com.lianyi.push.share.NettyConfig;
import com.lianyi.push.share.listener.TcpClientToSeiviceMessageListener;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * Created by leilei on 2018/8/15.
 */
@ChannelHandler.Sharable
public class TcpServerHandler extends ChannelInboundHandlerAdapter {
    private TcpClientToSeiviceMessageListener tcpServerListener;
    private int loss_connect_time = 0;
    private ExecutorService executorService = Executors.newFixedThreadPool(ConstantValue.TCP_MAX_COUNT);

    public TcpServerHandler(TcpClientToSeiviceMessageListener tcpServerListener) {
        this.tcpServerListener = tcpServerListener;
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端与服务端连接开始...");
        if (!NettyConfig.service_group.contains(ctx.channel())) {
            NettyConfig.service_group.add(ctx.channel());
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端与服务端连接关闭...");
        if (NettyConfig.service_group.contains(ctx.channel())) {
            NettyConfig.service_group.remove(ctx.channel());
        }
//        ctx.close();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {
                loss_connect_time++;
//                System.out.println("5 秒没有接收到客户端的信息了");
                if (loss_connect_time > 2) {
//                    System.out.println("关闭这个不活跃的channel");
//                    ctx.channel().close();
//                    loss_connect_time=0;
                }
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    /**
     * 服务端收到客户端消息
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        // 用于获取客户端发来的数据信息
        if (tcpServerListener != null) {
            tcpServerListener.tcpClientToSeiviceMessage(ctx, msg);
        }
//        System.out.println("Server接受的客户端的信息 :" + body.toString());
//        if (ConstantValue.HEAD_HEART_BEAT.equals(new String(body.getContent()))) {
////            LogUtil.e("Server接受的客户端的心跳数据", new String(body.getContent()) + "==" + ctx.channel().remoteAddress());
//        } else {
//            LogUtil.e("Server接受的客户端的信息", new String(body.getContent()) + "==" + ctx.channel().remoteAddress());
//            EventBus.getDefault().post(new FristTextEvent(new String(body.getContent()), ConstantValue.SERVICE_MESSAGE, 0));
//            if (new String(body.getContent()).contains("hospitalname") && new String(body.getContent()).contains("idcard")) {
//                Object jsondate = new JSONTokener(new String(body.getContent())).nextValue();
//                if (jsondate instanceof JSONObject) {
//                    try {
//                        JSONObject jsonObject = new JSONObject(new String(body.getContent()));
//                        String hospitalname = jsonObject.getString("hospitalname");
//                        String idcard = jsonObject.getString("idcard");
//                        int synctag = jsonObject.getInt("synctag");
////                        tcpServerListener.Redate(ctx, idcard, synctag);
////                        Redate(ctx, idcard, synctag);
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//        }
//        LogUtil.e("客户端的ip", ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().getHostName() + "==");
//        String str = new String(body.getContent());
//        SmartCarProtocol response = new SmartCarProtocol(str.getBytes().length,
//                str.getBytes());
////        NettyConfig.service_group.writeAndFlush(response);
//        Iterator<Channel> iterator = NettyConfig.service_group.iterator();
//        while (iterator.hasNext()) {
//            Channel channel = iterator.next();
////            LogUtil.e("打印出所有客户端的ip", ((InetSocketAddress)channel).getAddress().getHostName()+"==");
////            LogUtil.e("打印出所有客户端的远程地址", channel.remoteAddress() + "==");
//        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

}
